<template>
  <div v-if="showImportDialog">
    <el-dialog
      title="导入YAML"
      :visible.sync="showImportDialog"
      width="60%"
      :destroy-on-close="true"
      :before-close="beforeCloseDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div>
        <el-form :model="gvCloudYamlInfo" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <div style="width: 95%;">
            <el-row>
              <el-col :span="12">
                <el-form-item label="名称" prop="yamlZhname">
                  <el-input v-model="gvCloudYamlInfo.yamlZhname" style="width: 100%;"
                            placeholder="请输入yaml名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="标识" prop="yamlName">
                  <el-input v-model="gvCloudYamlInfo.yamlName" style="width: 100%;"
                            :disabled="type === 'edit'" placeholder="请输入yaml标识"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div style="width: 95%;">
            <el-row>
              <el-col :span="12">
                <el-form-item label="版本" prop="yamlVersion">
                  <el-input v-model="gvCloudYamlInfo.yamlVersion" style="width: 100%;"
                            :disabled="type === 'edit'"
                            placeholder="请输入yaml版本，如 0.0.0-xxx或0.0.0.0-xxx"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="描述" prop="yamlDescription">
                  <el-input type="textarea" v-model="gvCloudYamlInfo.yamlDescription" style="width: 100%;"
                            placeholder="请输入yaml描述信息"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <el-form-item label="上传文件" v-show="existFile === false || type !== 'edit'">
            <div style="display: flex; justify-content: left; width: 95%;">
              <el-upload
                class="upload-demo"
                action="#"
                :before-upload="handleBeforeUpload"
                :on-change="handleChange"
                multiple
                :limit="1"
                :auto-upload="false"
                accept=".yaml"
                :before-remove="beforeRemoveFile"
              >
                <el-button size="small" type="primary" :disabled="existFile"
                           class="el-button-primary-style"
                >点击上传
                </el-button>
              </el-upload>
              <el-tooltip class="item" effect="dark" content="注意事项" placement="right">
                <i class="el-icon-question" style="font-size: 25px; margin-left: 20px; margin-top: 7px; color: #304156"
                   @click="openAttentionDialog = true"></i>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item>
            <div style="overflow-y: scroll; max-height: 35vh; width: 95%;">
              <codemirror v-model="gvCloudYamlInfo.yamlContent" v-show="existFile" :options="cmOptions"
                          style="width: 40vw;"/>
            </div>
          </el-form-item>
          <el-form-item>
            <div style="display: flex; justify-content: right; width: 95%">
              <el-button type="primary" @click="submitForm()"
                         class="el-button-primary-style"
                         v-show="type === 'add'"
              >导入
              </el-button>
              <el-button type="primary" @click="submitForm()"
                         class="el-button-primary-style"
                         v-show="type === 'edit'"
              >修改
              </el-button>
              <el-button @click="closeImportDialog()" type="primary"
                         class="el-button-primary-style"
              >取消
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <el-dialog
      title="导入YAML文件注意事项"
      :visible.sync="openAttentionDialog"
      width="60%"
      append-to-body
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <div style="max-height: 60vh; overflow-y: scroll;">
        <div>
          <p>
            一、工作负载（Workloads）和资源管理（Resource Management）<br>
            导入的YAML文件只能包含以下工作负载（Workloads）和资源管理（Resource Management）的一种：<br>
            1、工作负载类型（Workload Types）：<br>
            ① Deployment：用于部署无状态应用，可以管理Pod和ReplicaSet。它具有上线部署、副本设定、滚动更新、回滚等功能，并支持声明式更新。<br>
            ② StatefulSet：用于部署有状态应用，它确保Pod具有唯一的标识和稳定的网络标识。StatefulSet常用于数据库等有状态服务的部署。<br>
            ③ DaemonSet：确保集群中的每个Node都运行一个Pod的副本。它常用于运行集群存储、日志收集、监控等需要在每个Node上运行的守护进程<br>
            2、资源管理类型（Resource Management Types）：<br>
            ④ Job：用于运行一次性任务，当任务完成时，Pod会终止。Job通常用于批处理任务。<br>
            ⑤ CronJob：基于时间的Job，用于在特定时间（如每天的某个时间点）运行周期性任务。
          </p>
        </div>
        <div>
          <p>
            二、镜像（images）<br>
            1、规则<br>
            所有镜像名必须以下面的格式开头: www.registry.it/<br>
            2、示例<br>
            image: www.registry.it/my-app:latest<br>
            三、存储<br>
            1、使用pvc模式<br>
            将hostpath模式修改为pvc模式，以下为修改示例：<br>
            修改前：
          </p>
        </div>
        <div>
          <codemirror v-model="yaml1" :options="cmOptions1" style="max-height: 600px;"></codemirror>
        </div>
        修改后：
        <div>
          <codemirror v-model="yaml2" :options="cmOptions1" style="max-height: 600px;"></codemirror>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {codemirror} from "vue-codemirror";
  import "codemirror/lib/codemirror.css";
  import "codemirror/mode/yaml/yaml.js";
  import jsyaml from 'js-yaml';

  export default {
    name: "ImportCloudYaml",
    components: {
      codemirror,
    },
    props: ["tmpGvCloudYamlInfo"],
    data() {
      return {
        showImportDialog: false,
        cmOptions: {
          mode: "yaml", // 使用YAML模式
          theme: "default", // 使用默认主题
          lineNumbers: true, // 显示行号
          line: true, // 显示行高亮
          styleActiveLine: true, // 高亮当前行
          matchBrackets: true, // 括号匹配高亮
          autoCloseBrackets: true, // 自动闭合括号
          gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], // 显示行号和折叠标记
          foldGutter: true, // 启用折叠功能
          extraKeys: {"Ctrl-Space": "autocomplete"}, // 添加自动完成快捷键
          // lineWrapping: true,
        },
        cmOptions1: {
          mode: "yaml", // 使用YAML模式
          theme: "default", // 使用默认主题
          lineNumbers: true, // 显示行号
          line: true, // 显示行高亮
          readOnly: true,
          scrollbarStyle: "null",
          // viewportMargin: 27
        },
        existFile: false,
        openAttentionDialog: false,
        type: "",
        gvCloudYamlInfo: {
          yamlZhname: "",
          yamlName: "",
          yamlVersion: "",
          yamlInterface: "",
          yamlDescription: "",
          yamlImages: "",
          yamlContent: "",
          newVersion: "",
        },
        rules: {
          yamlZhname: [
            {required: true, message: '请输入yaml名称', trigger: 'blur'},
            {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'},
            {
              pattern: /^([a-zA-Z0-9\u4e00-\u9fa5])*$/,
              message: "名称只能包含中文、字母、数字",
              trigger: ["blur", "change"],
            },
          ],
          yamlName: [
            {required: true, message: '请输入yaml标识', trigger: 'blur'},
            {min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'},
            {
              pattern: /^[a-zA-Z]([a-zA-Z0-9_])*$/,
              message: "标识只能包含字母、数字、_，且只能以字母开头",
              trigger: ["blur", "change"],
            },
          ],
          yamlVersion: [
            {required: true, message: '请输入yaml版本', trigger: 'blur'},
            {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'},
            {
              // pattern: /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?$/,
              pattern: /^(\d+)(\.(\d+))(\.(\d+))(\.(\d+))?([-]\w+)*(\+[a-zA-Z0-9-+]+)?$/,
              message: "版本格式为 0.0.0-xxx或0.0.0.0-xxx，主版本号、次版本号和修订号，版本号至少为0以及预发布标识符",
              trigger: ["blur", "change"],
            },
          ],
          // yamlDescription: [
          //   {required: true, message: '请输入yaml名称', trigger: 'blur'},
          //   {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
          // ],
        },
        yaml1: "apiVersion: v1  \n" +
          "kind: Deployment  \n" +
          "metadata:  \n" +
          "  name: my-deployment  \n" +
          "  labels:\n" +
          "    app: my-label\n" +
          "spec: \n" +
          "  selector:\n" +
          "    matchLabels:\n" +
          "      app: catalog\n" +
          "  template:\n" +
          "    metadata:\n" +
          "      labels:\n" +
          "        app: catalog\n" +
          "\tspec:\n" +
          "\t\tcontainers:  \n" +
          "\t\t- name: my-container  \n" +
          "\t\timage: www.registry.it/my-app:latest  \n" +
          "\t\tvolumeMounts:  \n" +
          "\t\t- name: my-host-volume  \n" +
          "\t\t\tmountPath: /data  \n" +
          "\t\t\treadOnly: false  \n" +
          "\t\tvolumes:  \n" +
          "\t\t- name: my-host-volume  \n" +
          "\t\thostPath:  \n" +
          "\t\t\tpath: /path/on/host  \n" +
          "\t\t\ttype: DirectoryOrCreate",
        yaml2: "apiVersion: v1  \n" +
          "kind: PersistentVolumeClaim  \n" +
          "metadata:  \n" +
          "  name: my-pvc  \n" +
          "spec:  \n" +
          "  accessModes:  \n" +
          "    - ReadWriteOnce  \n" +
          "  resources:  \n" +
          "    requests:  \n" +
          "      storage: 1Gi  \n" +
          "---  \n" +
          "apiVersion: v1  \n" +
          "kind: Deployment  \n" +
          "metadata:  \n" +
          "  name: my- deployment  \n" +
          "  labels:\n" +
          "    app: my-label\n" +
          "spec: \n" +
          "  selector:\n" +
          "    matchLabels:\n" +
          "      app: catalog\n" +
          "  template:\n" +
          "    metadata:\n" +
          "      labels:\n" +
          "        app: catalog\n" +
          "\tspec:\n" +
          "\t\tcontainers:  \n" +
          "\t\t- name: my-container  \n" +
          "\t\t  image: www.registry.it/my-app:latest  \n" +
          "\t\t  volumeMounts:  \n" +
          "          - name: my-volume  \n" +
          "            mountPath: /data  \n" +
          "        volumes:  \n" +
          "        - name: my-volume  \n" +
          "          persistentVolumeClaim:  \n" +
          "          claimName: my-pvc",
      }
    },
    methods: {
      submitForm() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (this.gvCloudYamlInfo.yamlContent === "") {
              this.$message.warning("yaml文件内容不能为空");
              return false;
            }
            try {
              this.gvCloudYamlInfo.yamlContent.split("---").forEach(ele => {
                jsyaml.load(ele);
              })
            } catch (e) {
              this.$message.error("yaml文件内容出现问题，请检查");
              console.log(e);
              return;
            }
            if (this.type === 'add') {
              this.$appStoreApi.uploadYaml(this.gvCloudYamlInfo).then(res => {
                if (res && res.code === 200) {
                  this.showImportDialog = false;
                  this.$message.success(res.data);
                  this.$emit("closeDialog");
                  this.$emit("initList");
                }
              })
            } else if (this.type === 'edit') {
              this.$appStoreApi.updateYaml(this.gvCloudYamlInfo).then(res => {
                if (res && res.code === 200) {
                  this.showImportDialog = false;
                  this.$message.success(res.data);
                  this.$emit("closeDialog");
                  this.$emit("initList");
                }
              })
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleBeforeUpload(file) {
        // 在这里可以进行文件上传前的处理，比如验证文件类型
        // 如果返回 false 或者返回 Promise 并且被 reject，那么上传动作会被终止
        // 这里简单返回 true 表示允许上传
        return true;
      },
      handleChange(file, fileList) {
        // 文件改变时的处理函数
        // 使用 FileReader 读取文件内容
        const reader = new FileReader();
        reader.onload = (e) => {
          // 处理文件内容
          this.gvCloudYamlInfo.yamlContent = e.target.result;
        };
        reader.readAsText(file.raw); // 读取文件内容为文本
        this.existFile = true;
      },
      beforeRemoveFile() {
        this.existFile = false;
        this.gvCloudYamlInfo.yamlContent = "";
      },
      beforeCloseDialog(done) {
        this.$emit("closeDialog");
        done();
      },
      closeImportDialog() {
        this.gvCloudYamlInfo = {
          yamlZhname: "",
          yamlName: "",
          yamlVersion: "",
          yamlInterface: "",
          yamlDescription: "",
          yamlImages: "",
          yamlContent: "",
          newVersion: "",
        };
        this.existFile = false;
        this.type = "";
        this.showImportDialog = false;
        this.$emit("closeDialog");
      }
    },
    beforeMount() {
      if (this.tmpGvCloudYamlInfo.yamlName !== "") {
        this.type = "edit";
        this.gvCloudYamlInfo = JSON.parse(JSON.stringify(this.tmpGvCloudYamlInfo));
        this.existFile = true;
      } else {
        this.type = "add";
      }
    },
  }
</script>

<style scoped>

</style>
